import { observable, action, autorun, toJS } from 'mobx';
import { WeaTableNew, WeaForm } from 'comsMobx';

const { TableStore } = WeaTableNew;
import { WeaTools } from 'ecCom';
import { message, Modal } from 'antd';
import * as Apis from '../apis/customerRightMenu';
import { crmAddFormRules } from '../util/index';
import { CustomerCardStore } from './customerCardStore';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

export class CrmInfoRightmenuStore /* extends CustomerCardStore */ {
    @observable modalInfo={
      modalTitle: getLabel(136, '客户'),
      modalStyle: { width: 446, height: 180 },
      modalType: '',
    }
    @observable customerId = '';
    @observable isShowModal = false;
    @observable form = new WeaForm();
    @observable customerMermgeForm = [];
    @observable statusChangeForm = [];
    applyPortalUrl = '';

    @observable businessInfoData = {} ; // 工商
    @observable businessTab = [{ key: '1', title: getLabel(130760, '工商信息') }, { key: '2', title: getLabel(83, '日志') }];
    @observable businessSelectKey = '1';
    @observable bussessMsgCode = '';
    @observable tableStore = new TableStore();
    @observable isShowShareDialog = false
    @observable customerinfo = {}

    @action
    saveCustomerId=(params) => {
      this.customerId = params.customerId;
    }
    // 导出客户联系
    contactLogExport=(id) => {
      Apis.contactLogExport({ customerId: id }).then((data) => {
        window.location = '/weaver/weaver.file.ExcelOut';
      });
    }
    // 发送邮件   key == 3
    addMailMenu =(id) => {
      Apis.addMailMenu({ customerIds: id }).then((data) => {
        // var url = "/email/new/MailInBox.jsp?opNewEmail=1&isInternal=0&to="+data.datas;
        const url = `/spa/email/static/index.html#/main/email/new?opNewEmail=1&isInternal=0&to=${data.datas}`;
        openFullWindowHaveBar(url);
      });
    }
  // 新建计划
    // addWorkPlan=(id)=>{
    //     // var url = "/workplan/data/WorkPlan.jsp?add=1&crmid="+id;
    //     var url = "/spa/workplan/index_mobx.html#/main/workplan/?add=1&crmid="+id;
    //     openFullWindowHaveBar(url);
    // }
    // 新建工作流
    addWorkflow = (id) => {
      const url = `/spa/workflow/static/index.html#/main/workflow/add?crmid=${id}`;
      openFullWindowHaveBar(url);
    }
   // 新建协作
  //    addCowork=(id)=>{
  //         // var url = "/workplan/data/WorkPlan.jsp?add=1&crmid="+id;
  //         var url = "/spa/cowork/index_mobx.html#/main/cowork/main?CustomerID="+id;
  //         openFullWindowHaveBar(url);
  //     }
   // dialog
   showDilog=(bool, params) => {
     //    console.log("bool",bool)
     //    console.log("params",params)
     this.isShowModal = bool;
     this.bussessMsgCode = '';

     if (bool) {
       this.modalInfo = params;
     }
   }
   showShareDilog=(bool) => {
     this.isShowShareDialog = bool;
   }
   // 客户合并   获取当前客户信息
   getUniteForm=(id) => {
     this.form = new WeaForm();
     Apis.getUniteForm({ customerId: id }).then((data) => {
       if (data.status == 'success') {
         this.customerId = id;
         this.customerMermgeForm = data.datas;
         this.form && !this.form.isFormInit && this.form.initFormFields(crmAddFormRules(data.datas));
       } else {
         message.error(getLabel(83437, '出现错误！') + data.msgcode);
       }
     });
   }
  // 客户合并  保存操作
    customerMergeSave=(customerId) => {
      const formParams = this.form.getFormParams();
      const that = this;
      this.form.validateForm().then((f) => {
        if (f.isValid) {
          // 如果主从客户一样，则直接关闭对话框
          let sub = `,${formParams.customerIds},`;
          const main = `,${formParams.customerId},`;
          if (sub === main) {
            that.showDilog(false);
            return;
          }

          // 如果从客户包含主客户，则去除从各户中的主客户
          if (sub.indexOf(main) > -1) {
            sub = sub.replace(main, ',');
            sub = sub.substring(1, sub.length - 1);
            formParams.customerIds = sub;
          }

          Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(15160, '确定要合并吗？'),
            onOk() {
              Apis.saveUniteForm(formParams).then((data) => {
                if (data.status == 'success') {
                  that.showDilog(false);
                  message.success(getLabel(33271, '合并成功'));
                  window.crm_store.customerCardStore.initCrmInfo({ customerId });
                  window.crm_store.customerCardStore.initTabDatas({ customerId });
                } else {
                  message.error(getLabel(83437, '出现错误！') + data.msgcode);
                }
              });
            },
            onCancel() {},
          });
        } else {
          f.showErrors();
               	// Modal.warning({
          //     title: getLabel(15172,"系统提示"),
          //     content: getLabel(15859,"必要信息不完整，红色标记为必填项！"),
          //     okText:getLabel(33703,"确定")
          // });
        }
      });
    }
    // 门户申请
    applyPortalManager =(url) => {
      const modalInfo = {
        modalTitle: getLabel(125283, '设置密码'),
        modalStyle: { width: 446, height: 150 },
        modalType: 'applyPortal',
      };
      this.applyPortalUrl = url;
      this.showDilog(true, modalInfo);
    }
    // 门户申请   密码保存
    applyPortalSave=(params = {}) => {
      Apis.doApply(params).then((data) => {
        if (data.status == 'success') {
          this.urlSubmit(this.applyPortalUrl);
          this.showDilog(false);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 修改密码
    setPasswdSave=(params) => {
      Apis.doApply(params).then((data) => {
        if (data.status == 'success') {
          this.showDilog(false);
          message.success(getLabel(83551, '保存成功！'));
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }

    // 申请->成功客户   key ==10
    urlSubmit =(url) => {
      const param = url.split('?')[1];
      const api = url.split('?')[0];
      const arr = param.split('&');
      const params = {};
      for (let i = 0; i < arr.length; i++) {
        const num = arr[i].indexOf('=');
        if (num > 0) {
          const name = arr[i].substring(0, num);
          const value = arr[i].substr(num + 1);
          params[name] = value;
        }
      }
      WeaTools.callApi(api, 'GET', params).then((data) => {
        if (data.status == 'success') {
          window.crm_store.customerCardStore.initCrmInfo({ customerId: this.customerId });
          window.crm_store.customerCardStore.initTabDatas({ customerId: this.customerId });
          message.success(getLabel(83551, '保存成功！'));
        } else {
          Modal.warning({
            title: getLabel(15172, '系统提示'),
            content: getLabel(132200, '操作失败！') + data.msgcode,
            okText: getLabel(33703, '确定'),
          });
        }
      });
    }
    // 删除用户
    deleteCustomer=(id) => {
      Apis.deleteCustomer({ customerIds: id }).then((data) => {
        if (data.status == 'success') {
          if (window.opener && window.opener._table !== undefined) {
            if (typeof window.opener._table.reLoad === 'function') { window.opener._table.reLoad(); }
          }
          window.crm_store.customerCardStore = new CustomerCardStore();
          window.close();
          weaHistory.push({
            pathname: '/main/crm/addCustomer',
          });
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 获取工商信息
    getBusinessInfo=(id) => {
      const modalInfo = {
        modalTitle: getLabel(130760, '工商信息'),
        modalStyle: { width: 830, height: 750 },
        modalType: 'business',
      };
      const that = this;
      Apis.getBusinessInfo({ customerId: id }).then((data) => {
        if (data.status == 'success') {
          const datas = data.datas;
          if (datas.fromCache) { // 取的缓存的数据
            that.businessInfoData = datas.businessInfoData.data;
            that.showDilog(true, modalInfo);
            Apis.saveBusinessLog({ customerId: id, requesttype: 1 }).then((data) => { // 保存日志
              // return true;
            });
          } else {
            const res = datas.businessInfoData;
            if (res.status == '200') {
              that.businessInfoData = res.data;
              that.showDilog(true, modalInfo);
              if (datas.isCache == '1') { // 缓存数据
                Apis.cacheBusinessInfo({ customerId: id, data: JSON.stringify(res) }).then((data) => {
                  // return true;
                });
              }
              Apis.saveBusinessLog({ customerId: id, requesttype: 0 }).then((data) => { // 保存日志
                // return true;
              });
            } else {
              message.error(res.message);
            }
            // let ajax = jQuery.ajax({
            //     url : encodeURI(datas.url),
            //     data:'{}',
            //     cache : false,
            //     async : true,
            //     type : "GET",
            //     dataType: "json",
            //     timeout:1000
            // });
            // ajax.done(function(data){
            //     if(data.status == "200"){
            //         that.businessInfoData = data.data;
            //         that.showDilog(true,modalInfo);
            //         if(datas.isCache=="1"){   //缓存数据
            //             Apis.cacheBusinessInfo({customerId:id,data:JSON.stringify(data)}).then(data=>{
            //                 // return true;
            //             })
            //         };
            //         Apis.saveBusinessLog({customerId:id,requesttype:0}).then(data=>{    //保存日志
            //             // return true;
            //         })
            //     }else{
            //         message.error(data.message);
            //     }
            // })
          }
        } else {
          message.error(data.msgcode);
        }
      });
    }
    changeBussessTab=(key, id) => {
      this.businessSelectKey = key;
      if (key == '2') {
        Apis.getBusinessLog({ customerId: id }).then((data) => {
          if (data.status == 'success') {
            this.tableStore.getDatas(data.sessionkey, 1);
			        this.dataKey = data.sessionkey;
          } else {
            message.error(getLabel(83437, '出现错误！') + data.msgcode);
          }
        });
      }
    }

    // 客户合并   获取当前客户信息
    getStatusChangeForm=(id) => {
      this.form = new WeaForm();
      Apis.getStatusChangeForm({ customerId: id }).then((data) => {
        if (data.status == 'success') {
          this.customerId = id;
          this.statusChangeForm = data.datas;
          this.form && !this.form.isFormInit && this.form.initFormFields(crmAddFormRules(data.datas));
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }

    // 状态变更  保存操作
    statusChangeSave=(customerId) => {
      const formParams = this.form.getFormParams();
      const that = this;
      this.form.validateForm().then((f) => {
        if (f.isValid) {
          // 如果主从客户一样，则直接关闭对话框
          const statusOld = formParams.statusOld;
          const statusNew = formParams.statusNew;

          if (statusOld === statusNew) {
            that.showDilog(false);
            return;
          }

          Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(32130, '确定要保存吗？'),
            onOk() {
              Apis.statusChangeSave({ customerId, ...formParams }).then((data) => {
                if (data.status == 'success') {
                  that.showDilog(false);
                  message.success(getLabel(83551, '保存成功'));
                  window.crm_store.customerCardStore.initCrmInfo({ customerId });
                  window.crm_store.customerCardStore.initTabDatas({ customerId });
                } else {
                  message.error(getLabel(83437, '出现错误！') + data.msgcode);
                }
              });
            },
            onCancel() {},
          });
        } else {
          f.showErrors();
        }
      });
    }
}
